package com.ruoyi.system.dao;

import com.ruoyi.common.core.dao.BaseDao;
import com.ruoyi.common.core.dao.dialect.FormatUtil;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.Page;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.ValidateUtil;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 字典表 数据层
 *
 * @author liuyj
 */
@Repository
public class SysDictDataDao extends BaseDao<SysDictData,Long> {
    /**
     * 根据条件分页查询字典数据
     *
     * @param dictData 字典数据信息
     * @return 字典数据集合信息
     */
    public Page findDictDataList(SysDictData dictData){
        PageDomain pageDomain = TableSupport.buildPageRequest();
        String hql="from SysDictData where 1=1 ";
        if (!ValidateUtil.isEmpty(dictData.getDictType())) {
            hql += " and dictType= '" + dictData.getDictType() + "'";
        }
        if (!ValidateUtil.isEmpty(dictData.getDictLabel())) {
            hql += " and dictLabel like '%" + dictData.getDictLabel() + "%'";
        }
        if (!ValidateUtil.isEmpty(dictData.getStatus())) {
            hql += " and status= '" + dictData.getStatus() + "'";
        }
        hql+="order by dictSort asc ";
        return this.findPage(hql, pageDomain.getPageNum(), pageDomain.getPageSize().intValue());
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    public List<SysDictData> findDictDataByType(String dictType){
        String hql="from SysDictData where status = '0' and dictType =?1 order by dictSort asc";
        return find(hql,dictType);
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     *
     * @param dictType 字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    public String selectDictLabel(String dictType,String dictValue){
        String dictLabel="";
        String hql="from SysDictData where dictType =? and dictValue=?";
        List<SysDictData> list=find(hql,new Object[]{dictType,dictValue});
        if (!ValidateUtil.isEmpty(list)){
            SysDictData sysDictData=list.get(0);
            dictLabel=sysDictData.getDictLabel();
        }
        return dictLabel;
    }

    /**
     * 查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据
     */
    public int countDictDataByType(String dictType){
        String hql = "select count(1) from SysDictData  where dictType = ?1";
        Long total = (Long) this.find(hql,dictType).get(0);
        return total.intValue();
    }

    /**
     * 同步修改字典类型
     *
     * @param oldDictType 旧字典类型
     * @param newDictType 新旧字典类型
     * @return 结果
     */
    public void updateDictDataType(String oldDictType, String newDictType){
        String hql="update SysDictData set dictType ="+ FormatUtil.formatStrForDB(newDictType);
        hql+=" where dictType="+FormatUtil.formatStrForDB(oldDictType);
        executeHql(hql);
    }
}
